import hashlib
from db_operations import DatabaseOperations


class Authentication:
    def __init__(self):
        self.db_ops = DatabaseOperations()

    def hash_password(self, password):
        return hashlib.sha256(password.encode()).hexdigest()

    def register_user(self, username, password, email=None):
        if self.db_ops.user_exists(username):
            return False, "用户名已存在"

        hashed_pw = self.hash_password(password)
        success = self.db_ops.create_user(username, hashed_pw, email)
        return success, "注册成功" if success else "注册失败"

    def login_user(self, username, password):
        hashed_pw = self.hash_password(password)
        return self.db_ops.verify_user(username, hashed_pw)